package com.gwt.auth.security;


import com.gwt.auth.config.AuthFilterConfig;
import com.gwt.auth.service.AuthService;
import com.gwt.auth.vo.AuthUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtTokenFilter extends OncePerRequestFilter {

    @Autowired
    private AuthService authService;

    @Autowired
    private AuthFilterConfig authFilterConfig;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        AuthUser authUser = authService.tokenValidate();
        //用户是否授权
        if (SecurityContextHolder.getContext().getAuthentication() == null) {
            //将User 封装到 securityContextHolder。 封装到securityContextHolder以后，其他过滤器就不会在拦截
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(authUser, null, null);
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        //设置Request-UserId
        request.setAttribute(authFilterConfig.getAuthUserIdKey(), authUser.getUserId());
        //设置Request-Token
        request.setAttribute(authFilterConfig.getAuthToken(), authUser.getToken());
        filterChain.doFilter(request, response);
    }
}
